package com.liohi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liohi.Param.R;
import com.liohi.entity.*;
import com.liohi.entity.vo.UserLoginVo;
import com.liohi.entity.vo.UserRegisterVo;
import com.liohi.mapper.UserMapper;
import com.liohi.service.*;
import com.liohi.tools.JwtUserInfo;
import com.liohi.tools.JwtUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
* @author liohi
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-08-02 15:10:31
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;
    @Override
    public R login(UserLoginVo user) {

        User curUser = this.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));

        if(Objects.isNull(curUser)){
            return R.error("账户不存在");
        }
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        if(user.getPassword().equals(curUser.getPassword())){
            //设置token
            String token = JwtUtils.getJwtToken(curUser.getUserId(), curUser.getName(), curUser.getType() );
            return R.ok("token",token);
        }
        return R.error("密码错误");
    }

    /**
     * 通过token拿到用户的菜单信息
     * @param token
     * @return
     */
    @Override
    public List<Menu> getMenusByToken(String token) {
        JwtUserInfo userInfoFromToken = JwtUtils.getUserInfoFromToken(token);

        List<Integer> roleIdsByUserId = userRoleService.getRoleIdsByUserId(userInfoFromToken.getUserId());

        List<Integer> menuIdsByRoleIds = roleMenuService.getMenuIdsByRoleIds(roleIdsByUserId);
        List<Menu> menus = menuService.getMenusByIds(menuIdsByRoleIds);

        return menus;
    }

    /**
     * 通过token拿到用户权限的路径
     * @param token
     * @return
     */
    @Override
    public List<String> getPathsByToken(String token) {

        List<Menu> menus = getMenusByToken(token);

        List<String> paths = new ArrayList<>();
        for (Menu menu : menus) {
            paths.add(menu.getEname());
        }
        return paths;
    }

    @Override
    public String getNameByToken(String token) {
        int userId = JwtUtils.getUserInfoFromToken(token).getUserId();
        User user = baseMapper.selectById(userId);

        return  user.getName();
    }

    @Override
    public User getUserByUsername(String username) {
        return baseMapper.selectOne(new QueryWrapper<User>().eq("username",username));
    }

    @Transactional
    @Override
    public R insertUser(UserRegisterVo user) {
        if(getUserByUsername(user.getUsername())!=null)return R.error("用户已存在");
        User insertUser = new User();
        BeanUtils.copyProperties(user,insertUser);

        // 使用MD5加密对密码进行加密
        String encryptedPassword = DigestUtils.md5Hex(user.getPassword());
        insertUser.setPassword(encryptedPassword);

        if ("教师".equals(user.getType())) {

            // 更新user表
            this.baseMapper.insert(insertUser);
            // 更新 teacher 表
            Teacher insertTeacher = new Teacher();
            insertTeacher.setUserId(insertUser.getUserId());
            insertTeacher.setTeacherNumber(user.getNumber());

            // 更新 user_role 数据表
            UserRole insertUserRole = new UserRole(insertUser.getUserId(),roleService.getRoleIdByName(user.getType()));
            userRoleService.getBaseMapper().insert(insertUserRole);

            // 将教师数据保存到"teacher"表中
            insertTeacher.setUserId(insertUser.getUserId());
            teacherService.insertTeacher(insertTeacher);
        } else if ("学生".equals(user.getType())) {
            // 将用户数据保存到"user"表中
            this.baseMapper.insert(insertUser);

            Student insertStudent = new Student();
            insertStudent.setUserId(insertUser.getUserId());
            insertStudent.setStudentNumber(user.getNumber());

            // 更新 user_role 数据表
            UserRole insertUserRole = new UserRole(insertUser.getUserId(),roleService.getRoleIdByName(user.getType()));
            userRoleService.getBaseMapper().insert(insertUserRole);

            // 将学生数据保存到"student"表中
            insertStudent.setUserId(insertUser.getUserId());
            studentService.insertStudent(insertStudent);
        } else {
            // 如果用户类型不支持，可以在这里处理
            return R.error("不支持的用户类型。");
        }
        return R.ok("注册成功");
    }


    @Transactional
    @Override
    public R updateUser(User user){
        // 更新user表
        baseMapper.updateById(user);
        // 更新 user_role 数据表
        Integer roleIdByName = roleService.getRoleIdByName(user.getType());
        Integer userId = user.getUserId();

        UpdateWrapper<UserRole> userRoleUpdateWrapper = new UpdateWrapper<>();
        userRoleUpdateWrapper.eq("user_id",userId);

        UserRole userRole = new UserRole();
        userRole.setRoleId(roleIdByName);

        if (userRoleService.update(userRole, userRoleUpdateWrapper)){
            return R.ok("修改成功");
        }else return R.error("修改失败");
    }
    @Override
    public String getAvatarByUserId(Integer userId) {
        return baseMapper.selectOne(new QueryWrapper<User>().eq("user_id", userId)).getAvatar();
    }

    @Override
    public List<User> getUserList() {
        return baseMapper.selectList(new QueryWrapper<User>().ne("type", "管理员"));
    }

    @Override
    public IPage<User> listByPage(Integer pageNum, Integer pageSize, String username, String name) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            if(username!=null&& !username.isEmpty())
                queryWrapper.like("username",username);
            queryWrapper.ne("type","管理员");
            if(name!=null && !name.isEmpty())
                queryWrapper.like("name",name);
            Page<User> page = new Page<>(pageNum, pageSize);

            return baseMapper.selectPage(page, queryWrapper);
    }
}




